﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework.Forms;
using Facebook;

namespace FBMarketing
{
    public partial class frmLogin : MetroForm
    {
        private string _loginUrl = "";
        public User CurrentUser = null;
        private bool _loggingOut;
        //-----------------------

        public frmLogin()
        {
            InitializeComponent();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            _loginUrl = Common.GenerateLoginUrl();
        }

        private void frmLogin_Shown(object sender, EventArgs e)
        {
            loginBrowser.Navigate(_loginUrl);
        }

        private void loginBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            loginBrowser.Visible = true;
            mpsLoading.Visible = false;
            //

            //if (loginBrowser.Visible)
            //{
                var fb = new FacebookClient();

                FacebookOAuthResult oauthResult;
                if (fb.TryParseOAuthCallbackUrl(e.Url, out oauthResult))
                {
                    if (oauthResult.IsSuccess)
                    {
                        Common.AccessToken = oauthResult.AccessToken;
                        Common.Authorized = true;
                    }
                    else
                    {
                        Common.AccessToken = "";
                        Common.Authorized = false;
                    }

                    if (Common.Authorized)
                    {
                        fb = new FacebookClient(Common.AccessToken);

                        dynamic result = fb.Get("me?fields=picture,email,name");

                        CurrentUser = new User();
                        CurrentUser.Id = result.id;
                        CurrentUser.Name = result.name;
                        CurrentUser.Email = result.email;
                        CurrentUser.Avatar = result.picture.data.url;

                      

                        //lblUsername.Text = string.Format("Facebook User: {0}", _currentName);
                        //RestoreXml();
                        //UpdateListView();
                        //updateBackgroundWorker.RunWorkerAsync();
                    }
                    else
                    {
                        MessageBox.Show("Couldn't log into Facebook!", "Login unsuccessful", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }

                    //fileToolStripMenuItem.Enabled = true;
                    //loginBrowser.Visible = false;
                    this.DialogResult = DialogResult.OK;
                    return;
                }
            //}

            if (_loggingOut)
            {
                if (loginBrowser.Document != null)
                {
                    HtmlElement logoutForm = loginBrowser.Document.GetElementById("logout_form");

                    if (logoutForm != null)
                    {
                        loginBrowser.Document.InvokeScript("execScript", new Object[] { "document.getElementById('logout_form').submit();", "JavaScript" });
                    }
                }

                if (e.Url.AbsoluteUri.StartsWith(@"https://www.facebook.com/index.php") || e.Url.AbsoluteUri.StartsWith(@"http://www.facebook.com/index.php"))
                {
                    if (Common.CloseAfterUpdateAndLogout)
                    {
                        Close();
                    }
                    else
                    {
                        //lblUsername.Text = "Facebook User: ---";
                        //totalLabel.Text = "";

                        _loggingOut = false;

                        CurrentUser.Name = "";
                        
                        Common.AccessToken = "";
                        Common.Authorized = false;
                        
                        //fileToolStripMenuItem.Enabled = false;
                        loginBrowser.Navigate(_loginUrl);
                    }
                }
            }

            if (e.Url.AbsoluteUri.Equals(_loginUrl))
            {
                //Hiện trang login
                loginBrowser.Visible = true;
            }
        }
    }
}
